package com.web;

import com.entity.Teacher;
import com.service.TeacherService;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/teacher")
public class TeacherServlet extends HttpServlet {

    //request对象
    private HttpServletRequest request;
    //response对象
    private HttpServletResponse response;

    private TeacherService teacherService = new TeacherService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //初始化请求和响应
        this.request = request;
        this.response = response;
        String method = request.getParameter("method");
        switch (method) {
            case "queryTeachers":  queryTeachers(); break;
        }
    }

    private void queryTeachers() {
        //1.过程太过复杂
        //2.不同的前端，处理数据情况不一样
        //3.定义的规则太随意，前端并不知道这个规则，规则混乱
        //4.传递数据的局限性，只能传递一种，只能传递用户信息或者其他信息，混在一起不好分割。
        List<Teacher> teachers = teacherService.queryTeachers();
        //id=1&name=张三,id=2&name=李四
        StringBuilder sbd = new StringBuilder();
        for (Teacher teacher : teachers) {
            sbd.append("id="+teacher.getId()).append("&name="+teacher.getName())
            .append(",");
        }
        sbd.append("&msg=成功");
        sbd.setLength(sbd.length()-1);
        WebUtils.sendMSG(response, sbd.toString());

    }
}
